package tech.mhuang.pacebox.springboot.payment.wechat.util;

import jakarta.servlet.http.HttpServletRequest;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import tech.mhuang.pacebox.core.util.CollectionUtil;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * mobile工具
 *
 * @author mhuang
 * @since 1.0.0
 */
public class MobileUtil {

    public static Map<String, String> parseXml(HttpServletRequest request)
            throws Exception {
        // 解析结果存储在HashMap
        Map<String, String> map = null;
        try (InputStream inputStream = request.getInputStream()) {
            // 读取输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();
            map = CollectionUtil.capacity(HashMap.class, elementList.size());
            // 遍历所有子节点
            for (Element e : elementList) {
                map.put(e.getName(), e.getText());
            }
        } finally {
            if (CollectionUtil.isEmpty(map)) {
                map = CollectionUtil.capacity(HashMap.class, 4);
            }
        }
        return map;
    }
}
